<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of "Login"
 *
 * Created on Dec 16, 2010
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */

class Login extends Controller {
	function Login() {
		parent::Controller();
	}
	
	function index() {
		$username = $this->input->post('username');
		$password = md5($this->input->post('password'));
		$error = false;
		
		// retrieve user data if email/password match
		$user = $this->db->query("SELECT id AS account_id, username, first_name, last_name, email, country_id, account_type, last_login FROM accounts WHERE username = ? AND password = ? AND account_type != 'agent' AND account_type != 'manager' LIMIT 1", array($username, $password));
		
		if($user->num_rows > 0) {
			// get row info
			$userdata = $user->row_array();
			
			// check if user is logged in
			if(!$this->common_model->isOnline($userdata['account_id'])) {
				// tie userdata to session
				$this->session->set_userdata($userdata);
				
				// add key
				$key =  md5('~qsysb~' . $this->session->userdata('account_id')); // key with salt
				$this->session->set_userdata(array('key' => $key));
				
				// get client data if company
				if($this->session->userdata('account_type') == 'company') {
					$client = $this->db->query("SELECT id AS client_id, name AS company_name, logo, validation_key, class_of_service FROM clients WHERE account_id = " . $this->session->userdata('account_id'));
					
					if($client->num_rows > 0) {
						// tie client data to session
						$clientdata = $client->row_array();
						$this->session->set_userdata($clientdata);
					} else {
						// invalid username or password
						$this->session->sess_destroy();
						$error = $this->lang->line('error_userpass');
					}
				}
				
				// get settings
				$this->load->model('settings_model');
				$settings = $this->settings_model->getConfig($this->session->userdata('account_type') == 'company' ? $this->session->userdata('client_id') : '');
				$this->session->set_userdata($settings);
			} else {
				// user is already logged in somewhere else
				$error = $this->lang->line('error_alreadyloggedin');
			}

			if($this->session->userdata('account_id')) {
				// update last user login
				$this->db->query("UPDATE accounts SET last_login = '" . time() . "' WHERE id = ?", array($this->session->userdata('account_id')));
			}
		} else {
			// invalid username or password
			$error = $this->lang->line('error_userpass');
		}
		
		// return result
		echo $error ? $error : '';
	}
}

/* End of file login.php */
/* Location: ./system/application/controllers/login.php */